package com.wzy.portfolio.utils;

import com.alibaba.fastjson2.JSON;
import com.wzy.portfolio.model.StockBaseDto;
import com.wzy.portfolio.model.StockHistoryReq;
import io.lettuce.core.RedisCommandTimeoutException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.RedisConnectionFailureException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Component
@Slf4j
public class RedisUtil {

    private RedisTemplate<String, Object> redisTemplate;

    public RedisUtil(RedisTemplate<String, Object> redisTemplate) {
        log.info("------->创建RedisUtil实例<--------");
        this.redisTemplate = redisTemplate;
    }

    /**
     * 指定缓存失效时间
     *
     * @param key  键
     * @param time 时间(秒)
     * @return
     */
    public boolean expire(String key, long time) {
        try {
            if (time > 0) {
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 判断key是否存在
     *
     * @param key 键
     * @return true 存在 false不存在
     */
    public boolean hasKey(String key) {
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 删除缓存
     *
     * @param key 可以传一个值 或多个
     */
    @SuppressWarnings("unchecked")
    public void del(String... key) {
        if (key != null && key.length > 0) {
            if (key.length == 1) {
                redisTemplate.delete(key[0]);
            } else {
                redisTemplate.delete((Collection<String>) CollectionUtils.arrayToList(key));
            }
        }
    }

    /**
     * 普通缓存获取
     *
     * @param key 键
     * @return 值
     */
    public Object get(String key) {
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }

    /**
     * 获取redis中包含prex的key对应的values值
     */
    public List<Map<String, String>> getValueByPrexKey(String prex) {
        List<Map<String, String>> list = new ArrayList<>();
        Set<String> keys = redisTemplate.keys(prex);// String prex = "hc-";//prex 为迷糊匹配的 key，如cache:user:*
        for (String key : keys) {
            SetOperations<String, Object> setOperations = redisTemplate.opsForSet();
            Set<Object> set = setOperations.members(key);
            for (Object obj : set) {
                Map<String, String> map = (Map<String, String>) obj;
                list.add(map);
            }
        }
        return list;
    }

    /**
     * 普通缓存放入
     *
     * @param key   键
     * @param value 值
     * @return true成功 false失败
     */
    public boolean set(String key, Object value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 普通缓存放入并设置时间
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒) time要大于0 如果time小于等于0 将设置无限期
     * @return true成功 false 失败
     */
    public boolean set(String key, Object value, long time) {
        try {
            if (time > 0) {
                redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            } else {
                set(key, value);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 将list写入Redis队列中
     * @param key
     * @param list
     */
    public void pushQueue(String key, StockHistoryReq req, List<StockBaseDto> list) {
        for(int m = 0; m < list.size(); m++) {
            StockBaseDto dto = list.get(m);
            dto.setBeg(req.getStartDate());
            dto.setEnd(req.getEndDate());
            redisTemplate.opsForList().rightPush(key,dto );
        }
    }

    /**
     * 从队列中获取数据
     * @param key
     */
    @Retryable(
            value = {RedisConnectionFailureException.class, RedisCommandTimeoutException.class},
            maxAttempts = 10,
            backoff = @Backoff(delay = 1000, multiplier = 2)
    )
    public StockBaseDto leftPop(String key){
        Object o = redisTemplate.opsForList().leftPop(key);
        if(o==null){
            return null;
        }else {
            return JSON.parseObject(o.toString(),StockBaseDto.class) ;
        }
    }

    @Retryable(
            value = {RedisConnectionFailureException.class, RedisCommandTimeoutException.class},
            maxAttempts = 10,
            backoff = @Backoff(delay = 1000, multiplier = 2)
    )
    public void pushQueueOne(String key, StockBaseDto dto) {
        redisTemplate.opsForList().rightPush(key, dto);
    }

    public Long hasValueInQueue(String queueKey) {
        // 获取队列长度
        Long size = redisTemplate.opsForList().size(queueKey);
        // 判断长度是否大于0。注意：如果键不存在，size也为null，需要处理
        return size;
    }

}
